# -*- coding:utf-8 -*-

from flask import abort
from flask import json
from flask import render_template
from flask import request
from flask_login import login_required
from sqlalchemy import desc

from app.actions.tag import tag
from app.database.models import Tag

__author__ = 'JiangW'


@tag.route('/', methods=['GET'])
def tag_list():
    query_dict = {
        'is_active': True,
    }

    page = request.args.get('page', 1, type=int)
    pagination = Tag.query.filter_by(**query_dict).order_by(desc(Tag.update_on)).paginate(
        page, per_page=20, error_out=False)
    return render_template('tag/tag_list.html', pagination=pagination)


@tag.route('/edit', methods=['GET', 'POST'])
@login_required
def tag_create():
    if request.method == 'GET':
        return render_template('tag/tag_edit.html')
    else:
        res = {'code': 1000}
        tag_name = request.values.get('tag_name')
        if tag_name:
            Tag(name=tag_name).save()
        else:
            res['code'] = 1001
        return json.dumps(res)


@tag.route('/edit/<int:tag_id>', methods=['GET', 'POST'])
@login_required
def tag_edit(tag_id):
    current_tag = Tag.query.get(int(tag_id))
    if current_tag:
        if request.method == 'GET':
            return render_template('tag/tag_edit.html', current_tag=current_tag)
        else:
            res = {'code': 1000}
            tag_name = request.values.get('tag_name')
            if tag_name:
                current_tag.name = tag_name
                current_tag.save()
            else:
                res['code'] = 1001
            return json.dumps(res)
    else:
        abort(404)


@tag.route('/delete/<int:tag_id>', methods=['GET', 'POST'])
@login_required
def tag_delete(tag_id):
    current_tag = Tag.query.get(int(tag_id))
    if current_tag:
        if request.method == 'GET':
            return render_template('tag/tag_delete.html', current_tag=current_tag)
        else:
            res = {'code': 1000}
            current_tag.delete()
            return json.dumps(res)
    else:
        abort(404)


@tag.route('/cloud', methods=['GET'])
def tag_cloud():
    cloud_words_list = []
    max_size = 88.0
    max_appearance = 1

    query_dict = {
        'is_active': True,
    }
    current_tag_list = Tag.query.filter_by(**query_dict)
    for current_tag in current_tag_list:
        single_appearance = current_tag.blogs.count()
        if single_appearance > max_appearance:
            max_appearance = single_appearance
        word_dict = {
            'text': current_tag.name,
            'single_appearance': single_appearance,
        }
        cloud_words_list.append(word_dict)

    for cloud_word in cloud_words_list:
        cloud_word['size'] = max_size / max_appearance * cloud_word['single_appearance']

    cloud_words_json = json.dumps(cloud_words_list)
    return render_template('tag/tag_cloud.html', cloud_words_json=cloud_words_json)

